#!/usr/bin/perl

# This script scans (an HDHR3-US) and creates a directory full of strm files ready to be used by XBMC
# Copyright 2011 by jwater7 under the terms of the GNU General Public License
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


use warnings;
use strict;

$|=1; #disable output buffer

# Find hdhr_config
chomp(my $hdhr_config = `which hdhomerun_config`);
if (! -e $hdhr_config) {
	print "ERROR: hdhomerun_config must be in your path\n";
	exit 1;
}

# Make the output directory
if(! -d "HDHR_chans") {
	print "Making $ENV{PWD}/HDHR_chans directory...\n";
	print "\t(look in here for the strm files)...\n";
	mkdir ("HDHR_chans");
}

chomp(my $device = `$hdhr_config discover`);
$device =~ /device (.*) found/;
$device = $1;
print "Device found at: $device\n";

my $tuner = '1';

print "Scanning for channels using tuner$tuner...\n";
#my @scan_out = `$hdhr_config $device scan /tuner1`;
if (open(SCANR, "$hdhr_config $device scan /tuner$tuner |")) {
	my $chan = '';
	while (my $line = <SCANR>) {
		chomp($line);
		# Look for the start of a channel (like 51)
		if ($line =~ m/SCANNING.*:([0-9]+)/) {
			$chan = $1;
		}
		# Look for the program number (like 7.1)
		if ($line =~ m/PROGRAM.*:\s([0-9]+.[0-9]+)\s(.*)/) {
			my $prog = $1;
			my $cname = $2;
			$cname =~ s/\s/_/;
			print "Found Program $prog-$cname on channel $chan\n";
			print `echo 'hdhomerun://$device-$tuner/tuner$tuner?channel=auto:$chan&program=$prog' > HDHR_chans/$prog-$cname-tuner$tuner.strm`;
		}
	}
}

print "Done.\n";
exit 0;

